package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.mapper.DubboCartMapper;
import com.jt.pojo.Cart;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class DubboCartServiceImpl implements DubboCarService{

    @Autowired
    private DubboCartMapper dubboCartMapper;

    @Override
    public List<Cart> findCartById(Long userId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        return dubboCartMapper.selectList(queryWrapper);
    }

    /**
     * 需求:更新购物车数量num
     * @param cart
     */
    @Override
    public void updateCartNum(Cart cart) {
        Cart cart1 = new Cart();
        cart1.setNum(cart.getNum());
        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id",cart.getUserId()).eq("item_id",cart.getItemId());
        dubboCartMapper.update(cart1,updateWrapper);
    }

    @Override
    public void deleteCart(Cart cart) {
        dubboCartMapper.delete(new QueryWrapper<>(cart));
    }

    /**
     * 思路:
     *  1.查询数据库userId ItemId
     *  2.判断返回值是否有结果
     *      true:num+1
     *      false:直接入库
     * @param cart
     */
    @Override
    public void addCart(Cart cart) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cart.getUserId())
                .eq("item_id",cart.getItemId());
        Cart cart1 = dubboCartMapper.selectOne(queryWrapper);
        if(cart1==null){
            dubboCartMapper.insert(cart);
        }else {
            int num = cart.getNum()+cart1.getNum();
            cart1.setNum(num).setUpdated(new Date());
            dubboCartMapper.updateCartNum(cart1);
        }
    }
}
